// 用于创建 store
import { configureStore, combineReducers } from "@reduxjs/toolkit";
/**
 * persistReducer  一个对 reducer 进行 persist 处理的
 */
import { persistReducer, persistStore } from "redux-persist";
// localStorage     redux-persist/lib/storage
// sessionStorage   redux-persist/lib/storage/session
import storage from "redux-persist/lib/storage";

// 引入切片的 reducer
import { reducer as appReducer } from "@/stores/app";
import { reducer as cartReducer } from "@/stores/cart";
import { reducer as userReducer } from "@/stores/user";

// 使用 combineReducers 来组合 rootReducer, 处理 下方 RootState TS类型不正确的问题
const rootReducer = combineReducers({
  app: persistReducer(
    {
      key: "app", // 用于给存储取key的名字，前缀为 "persist:", 最终 "persist:app"
      storage, // 设置储存在哪儿
      // blacklist: ["path"], // 设置黑名单
    },
    appReducer
  ),
  cart: persistReducer(
    {
      key: "cart",
      storage,
      blacklist: ["msg"],
    },
    cartReducer
  ),
  user: persistReducer(
    {
      key: "user",
      storage,
    },
    userReducer
  ),
});

const store = configureStore({
  reducer: rootReducer,
  // 配置不需要做序列化检查，主要处理使用了 redux-persist 后报错的一个小问题
  middleware: (getDefaultMiddleware) => {
    return getDefaultMiddleware({
      serializableCheck: false,
    });
  },
});

// 从 store 本身推断出 `RootState` 类型
//    typeof store.getState 得到 store.getState 这个函数的类型
//    ReturnType 得到返回值的类型
export type RootState = ReturnType<typeof store.getState>;

// PS: 取操作处理
persistStore(store);

export default store;
